package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.NetworkConstant;
import com.zb.constant.WorkConstant;
import com.zb.entity.ZjNetwork;
import com.zb.entity.ZjWorkDispatchEngineer;
import com.zb.entity.ZjWorkDispatchNetwork;
import com.zb.extend.NetworkDispatchOrderListExtend;
import com.zb.mapper.ZjWorkDispatchNetworkMapper;
import com.zb.mobile.NetworkMobileOrderListSelectVo;
import com.zb.mobile.NetworkMobileOrderMessageListSelectVo;
import com.zb.mobile.NetworkOrderStatusQtyVo;
import com.zb.service.*;
import com.zb.job.NetworkDispatchTimeoutJob;
import com.zb.job.NetworkReceiveTimeoutJob;
import com.zb.utils.ZbDateConvertUtil;
import com.zb.view.ViewNetworkEmpDetail;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 工单分派网点表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-23
 */
@Service
public class ZjWorkDispatchNetworkServiceImpl extends ServiceImpl<ZjWorkDispatchNetworkMapper, ZjWorkDispatchNetwork> implements ZjWorkDispatchNetworkService {
    @Resource
    private ZjWorkDispatchNetworkMapper workDispatchNetworkMapper;
    @Resource
    private ZjNetworkService networkService;
    @Resource
    private ZjNetworkStrategyService networkStrategyService;
    @Resource
    private ViewNetworkEmpDetailService viewNetworkEmpDetailService;
    @Resource
    private ZjWorkDispatchEngineerService workDispatchEngineerService;

    // 保存工单分派服务商
    @Override
    public void save(Long custAccId, Long workId, Long networkId) {
        if (null == networkId || networkId == 0) {
            return;
        }
        ZjWorkDispatchNetwork dispatchNetwork = getByWorkId(workId);
        if (null == dispatchNetwork) {
            ZjNetwork network = networkService.getById(networkId);
            // 服务商是否自动确认接单，默认为false
            boolean networkSureReceiveOrder = false;
            if (network.getCategory() == NetworkConstant.CATEGORY_1) {
                networkSureReceiveOrder = networkStrategyService.isAutoSureReceiveOrder(networkId).getAutoSureReceiveOrder();
            }
            dispatchNetwork = new ZjWorkDispatchNetwork();
            dispatchNetwork.setId(IdWorker.getId());
            dispatchNetwork.setCustAccId(custAccId);
            dispatchNetwork.setWorkId(workId);
            dispatchNetwork.setNetworkId(networkId);
            dispatchNetwork.setStatus(network.getCategory() == NetworkConstant.CATEGORY_2? WorkConstant.DISPATCH_NETWORK_STATUS_1 : networkSureReceiveOrder? WorkConstant.DISPATCH_NETWORK_STATUS_2 : WorkConstant.DISPATCH_NETWORK_STATUS_1);
            dispatchNetwork.setTransferOrderWaitCheck(false);
            dispatchNetwork.setDispatchTime(new Date());
            dispatchNetwork.setReceivingOrderTime(dispatchNetwork.getStatus() == WorkConstant.DISPATCH_NETWORK_STATUS_2? new Date() : null);
            dispatchNetwork.setRemark("");
            if (network.getTeamType() == 2) {
                ViewNetworkEmpDetail networkEmpDetail = viewNetworkEmpDetailService.getManagerByNetworkId(networkId);
                ZjWorkDispatchEngineer engineer = new ZjWorkDispatchEngineer();
                engineer.setId(IdWorker.getId());
                engineer.setCustAccId(custAccId);
                engineer.setWorkId(workId);
                engineer.setNetworkId(networkId);
                engineer.setNetworkEmpId(networkEmpDetail.getId());
                engineer.setStatus(WorkConstant.DISPATCH_ENGINEER_STATUS_2);
                engineer.setDispatchTime(ZbDateConvertUtil.dateToDateStr(new Date()));
                engineer.setDispatchRemark("");
                engineer.setReceivingOrderTime(ZbDateConvertUtil.dateToDateStr(new Date()));
                engineer.setReservation(false);
                engineer.setReservationDate("");
                engineer.setReservationStartTime("");
                engineer.setReservationEndTime("");
                engineer.setNetworkEmpFinishTime("");
                engineer.setRemark("");
                engineer.setCallPhoneQty(0);
                engineer.setCallPhoneTime("");
                engineer.setWriteCallPhoneResult(false);
                engineer.setSignIn(false);
                workDispatchEngineerService.save(engineer);
                dispatchNetwork.setStatus(WorkConstant.DISPATCH_NETWORK_STATUS_4);
             }
            this.save(dispatchNetwork);
            if (networkSureReceiveOrder){
                try {
                    new NetworkDispatchTimeoutJob(dispatchNetwork.getCustAccId(), dispatchNetwork.getId());
                } catch (SchedulerException e) {
                    throw new RuntimeException("创建服务商超时未派单任务失败",e);
                }
            }else {
                try {
                    new NetworkReceiveTimeoutJob(dispatchNetwork.getCustAccId(), dispatchNetwork.getId());
                } catch (SchedulerException e) {
                    throw new RuntimeException("创建服务商超时未接单任务失败", e);
                }
            }
        }
    }

    // 根据ID更新重复派单的派单记录
    @Override
    public void updateRepeatDispatchOrderById(List<ZjWorkDispatchNetwork> updateDispatchNetwork) {
        if (CollectionUtil.isEmpty(updateDispatchNetwork)) {
            return;
        }
        UpdateWrapper<ZjWorkDispatchNetwork> updateWrapper = null;
        for (ZjWorkDispatchNetwork dispatchNetwork : updateDispatchNetwork) {
            updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", dispatchNetwork.getId());
            updateWrapper.set("cust_acc_id", dispatchNetwork.getCustAccId());
            updateWrapper.set("work_id", dispatchNetwork.getWorkId());
            updateWrapper.set("network_id", dispatchNetwork.getNetworkId());
            updateWrapper.set("status", dispatchNetwork.getStatus());
            updateWrapper.set("dispatch_time", dispatchNetwork.getDispatchTime());
            updateWrapper.set("receiving_order_time", dispatchNetwork.getReceivingOrderTime());
            updateWrapper.set("change_time", dispatchNetwork.getChangeTime());
            updateWrapper.set("remark", StringUtils.isNotBlank(dispatchNetwork.getRemark())? dispatchNetwork.getRemark() : "");
            this.update(updateWrapper);
        }
    }

    // 根据ID更新重复派单的派单记录
    @Override
    public void updateRepeatDispatchOrderById(ZjWorkDispatchNetwork updateDispatchNetwork) {
        List<ZjWorkDispatchNetwork> updateDispatchNetworks = new ArrayList<>();
        updateDispatchNetworks.add(updateDispatchNetwork);
        updateRepeatDispatchOrderById(updateDispatchNetworks);
    }

    // 根据工单ID获取服务商信息
    @Override
    public ZjWorkDispatchNetwork getByWorkId(Long workId) {
        QueryWrapper<ZjWorkDispatchNetwork> wrapper = new QueryWrapper<>();
        wrapper.eq("work_id", workId)
                .between("status",  WorkConstant.DISPATCH_NETWORK_STATUS_1,  WorkConstant.DISPATCH_NETWORK_STATUS_6);
        return this.getOne(wrapper);
    }

    // 根据服务商ID分页获取工单ID
    @Override
    public List<Long> getWorkIdByNetworkId(Long networkId, NetworkMobileOrderMessageListSelectVo selectVo) {
        QueryWrapper<ZjWorkDispatchNetwork> wrapper = new QueryWrapper<>();
        wrapper.select("work_id");
        wrapper.eq("network_id", networkId);
        if (null != selectVo.getStatus()) {
            wrapper.eq("status", selectVo.getStatus());
        }
        return this.list(wrapper).stream().map(ZjWorkDispatchNetwork::getWorkId).toList();
    }

    // 根据服务商ID & 工单ID获取工单分派服务商信息
    @Override
    public List<ZjWorkDispatchNetwork> getByNetworkIdAndWorkIds(Long networkId, List<Long> workIds) {
        if (CollectionUtil.isEmpty(workIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkDispatchNetwork> wrapper = new QueryWrapper<>();
        wrapper.select("work_id", "status");
        wrapper.eq("network_id", networkId);
        wrapper.in("work_id", workIds);
        wrapper.between("status",  WorkConstant.DISPATCH_NETWORK_STATUS_1,  WorkConstant.DISPATCH_NETWORK_STATUS_7);
        return this.list(wrapper);
    }

    // 根据工单ID与服务商ID获取派单信息
    @Override
    public ZjWorkDispatchNetwork getByWorkIdAndNetowrkId(Long workId, Long networkId) {
        QueryWrapper<ZjWorkDispatchNetwork> wrapper = new QueryWrapper<>();
        wrapper.eq("network_id", networkId).eq("work_id", workId);
        return this.getOne(wrapper);
    }

    // 获取服务商移动端工单列表
    @Override
    public List<NetworkDispatchOrderListExtend> getNetworkOrderList(Long custAccId, Long networkId, NetworkMobileOrderListSelectVo selectVo) {
        return workDispatchNetworkMapper.getNetworkOrderList(custAccId, networkId, selectVo);
    }

    // 获取服务商工单列表状态数量
    @Override
    public NetworkOrderStatusQtyVo getNetworkOrderListStatusQty(Long custAccId, Long networkId, String keyword) {
        NetworkOrderStatusQtyVo networkOrderListStatusQty = workDispatchNetworkMapper
                .getNetworkOrderListStatusQty(custAccId, networkId, keyword);
        // 新增待核销
        Long isHxTotal = workDispatchNetworkMapper.getIsHxTotal();
        Long isPauseTotal = workDispatchNetworkMapper.getIsPauseTotal();
        networkOrderListStatusQty.setHxWaitQty(isHxTotal);
        networkOrderListStatusQty.setIsPauseQty(isPauseTotal);
        long waitCheckTotal = networkOrderListStatusQty.getFeeWaitCheckQty() + networkOrderListStatusQty.getSpareWaitCheckQty() +
                networkOrderListStatusQty.getTransferOrderWaitCheckQty() + networkOrderListStatusQty.getCancelOrderWaitCheckQty() +
                networkOrderListStatusQty.getChangeOrderWaitCheckQty();
        networkOrderListStatusQty.setWaitCheckQty(waitCheckTotal);
        return networkOrderListStatusQty;
    }

    // 获取服务商移动端工单列表总记录数
    @Override
    public long getNetworkOrderListCount(Long custAccId, Long networkId, NetworkMobileOrderListSelectVo selectVo) {
        return workDispatchNetworkMapper.getNetworkOrderListCount(custAccId, networkId, selectVo);
    }

    // 根据工单ID与服务商ID查询已存在的工单
    @Override
    public List<ZjWorkDispatchNetwork> getOrderDispatchHistoryByWorkIdsAndNetworkId(Long networkId, List<Long> workIds) {
        if (CollectionUtil.isEmpty(workIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkDispatchNetwork> wrapper = new QueryWrapper<>();
        wrapper.eq("network_id", networkId).in("work_id", workIds);
        return this.list(wrapper);
    }

    // 根据工单ID获取服务商待接单的工单
    @Override
    public List<ZjWorkDispatchNetwork> getWaitReceiveOrderByWorkIds(List<Long> workIds) {
        if (CollectionUtil.isEmpty(workIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkDispatchNetwork> wrapper = new QueryWrapper<>();
        wrapper.eq("status", WorkConstant.DISPATCH_NETWORK_STATUS_1)
                .in("work_id", workIds);
        return this.list(wrapper);
    }

}
